import {normalize, join, sep} from 'node:path';
import {readFileSync} from 'node:fs';
import {pkgPath, clientPath, htmlTemplatePath, assetParam} from './util/paths.mjs';
import {serveAsset, servePage} from './util/serveStatic.mjs';

function createAppHandler() {
  const htmlTemplate = readFileSync(htmlTemplatePath).toString();

  const appHandler = (req, res) => {
    const assetIndex = req.url.indexOf(assetParam);

    if (assetIndex < 0) {
      servePage(req, res, htmlTemplate);
      return;
    }

    let url = req.url.substring(assetIndex + assetParam.length);
    url = normalize(url).replaceAll('..' + sep, '');
    if (url.startsWith('node_modules/')) {
      serveAsset(res, join(pkgPath, url));
    } else {
      serveAsset(res, join(clientPath, url));
    }
  };

  return appHandler;
}

export default createAppHandler;
